package com.gyms.behavior;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import utils.AnimotionUtils;


/**
 * Created by ltx on 17/9/1
 * 返回顶部 的behavior
 */

public class FabBehavior extends FloatingActionButton.Behavior {
    public boolean visible = true;//是否可见
    private int mScrollHight;//向下滚动的距离
    private int mScreenHight;//屏幕的高度

    public FabBehavior(Context context, AttributeSet attrs) {
        super();
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
                                       FloatingActionButton child, View directTargetChild, View target,
                                       int nestedScrollAxes) {
        // 当观察的View（RecyclerView）发生滑动的开始的时候回调的
        //nestedScrollAxes:滑动关联轴， 我们现在只关心垂直的滑动。
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild,
                target, nestedScrollAxes);
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout,
                               FloatingActionButton child, View target, int dxConsumed,
                               int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed,
                dxUnconsumed, dyUnconsumed);
        //根据情况执行动画
        if(mScrollHight<mScreenHight){//保证第一页不会出现
            visible = false;
            AnimotionUtils.onHide(child);
        }else if (dyConsumed > 0 && visible) {
            visible = false;
            AnimotionUtils.onHide(child);
        } else if (dyConsumed < 0) {
            visible = true;
            AnimotionUtils.onShow(child);
        }
    }

    public static <V extends View> FabBehavior from(V view) {
        ViewGroup.LayoutParams params = view.getLayoutParams();
        if (!(params instanceof CoordinatorLayout.LayoutParams)) {
            throw new IllegalArgumentException("The view is not a child of CoordinatorLayout");
        }
        CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) params).getBehavior();
        if (!(behavior instanceof FabBehavior)) {
            throw new IllegalArgumentException("The view is not associated with ScaleDownShowBehavior");
        }
        return (FabBehavior) behavior;
    }

    /**
     * 设置屏幕的高度
     * @param mScreenHight 屏幕高度
     */

    public void setScreenHight(int mScreenHight) {
        this.mScreenHight = mScreenHight;
    }

    /**
     * 向下滚动的距离
     * @param mScrollHight 滚动的距离
     */

    public void setScrollHight(int mScrollHight) {
        this.mScrollHight = mScrollHight;
    }

}
